package com.largeOrange.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.largeOrange.myexception.ConnectionCategoryException;
import com.largeOrange.pojo.Employee;
import com.largeOrange.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 大橙子
 * @version 1.0
 * @since 1.0
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
//@ResponseBody的作用其实是将java对象转为json格式的数据。
public class GlobalExceptionHandler {
    @Autowired
    private EmployeeService service;
    /**
     * 配置异常捕获器
     * @return
     */
    //SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan' for key 'idx_username'
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        String message=exception.getMessage();
        log.info(message);
        if (message.contains("idx_username")){
            String[] split = message.split("'");
            String name=split[1];
            log.info(name);
            String name01="zhangSan";
            log.info(name01);
            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Employee::getUsername,name);
            Employee one = service.getOne(wrapper);
            return R.error(one.getName()+"员工已存在，请重新添加！");
        }

        if (message.contains("idx_category_name")){
            String[] split = message.split(" ");
            String category = split[2];
            return R.error(category+"已存在，请重新修改或重新添加！");
        }
        return R.error("添加失败，未知原因！");
    }
    //SQLIntegrityConstraintViolationException: Duplicate entry '大橙子超级套餐' for key 'idx_category_name'
    //ConnectionCategoryException
    @ExceptionHandler(ConnectionCategoryException.class)
    public R<String> connectionCategory(ConnectionCategoryException exception){
        String message = exception.getMessage();
        return R.error(message);
    }
}
